package com.finance.cooperate.feature.thread;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ArrayBlockingQueue;

/**
 * @ClassName ReaderQueue
 * @Description Reader处理队列
 * @Author shen
 * @Date 2022/5/26 11:43
 * @Modify ...
 */
public class ReaderQueue {

    private ArrayBlockingQueue<Map<String, String>> queue = new ArrayBlockingQueue<Map<String, String>>(5000);


    public void put(Map<String, String> model) {
        try {
            queue.put(model);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public Map<String, String> take() {
        try {
            return queue.take();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public List<Map<String, String>> drainTo() {
        List<Map<String, String>> result = new ArrayList<>();

        try {
            //为什么调用一次take，因为drainTo不阻塞
            Map<String, String> take = queue.take();
            queue.drainTo(result, 1000);
            result.add(take);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }



    private static class Singleton {

        private static ReaderQueue instance;

        static {
            instance = new ReaderQueue();
        }

        public static ReaderQueue getInstance() {
            return instance;
        }

    }

    public static ReaderQueue getInstance() {
        return Singleton.getInstance();
    }

    public static void init() {
        getInstance();
    }
}
